<?php

namespace App\Job\Auto;

use App\Actions\ChatAction;
use App\Dao\AutoReplyDao;
use App\Dao\CommonSettingDao;
use App\Dao\GreetMasterDao;
use App\Dao\PhotoDao;
use App\Dao\UserTeaseDao;
use App\Model\AutoChat;
use App\Model\User;
use App\Services\PushMessageService;
use App\Utils\LoggerUtil;
use App\Utils\RedisClient;
use Hyperf\AsyncQueue\Job;
use function Hyperf\Config\config;

/**
 * Note - 主播对在线用户自动聊天
 * DateTime 2024/9/2 12:30
 * User Admin
 * Class ChatResQueueJob
 * @package App\Job\Auto
 */
class ChatResQueueJob extends Job
{
    private mixed $data;

    public function __construct($data)
    {
        // 这里最好是普通数据，不要使用携带 IO 的对象，比如 PDO 对象
        $this->data = $data;
    }

    public function handle()
    {
        // TODO: Implement handle() method.
        try {
            $body = json_decode($this->data, true);
            LoggerUtil::write("auto_chat_queue_job", $body);
            $this->run($body);
        } catch (\Exception $e) {
            LoggerUtil::write("auto_chat_queue_job", [$e->getMessage(), $e->getFile(), $e->getLine()]);
        }
    }


    private function run(mixed $body)
    {
        $uid = $body['uid'];
        $data = RedisClient::getInstance()->hGet('auto_chat_res', strval($uid));
        $json = json_decode($data, true);
        $out_users = $json['users'] ?? [];// 屏蔽用户（已经发过私信的主播）
        $maskIds = (new ChatAction())->getMaskUsers($uid);
        $maskIds = array_merge($out_users, $maskIds);
        $anchorUser = $this->getPriorAnchor($uid, $maskIds);
        if ($anchorUser) {
            $anchor = $anchorUser['id'];
            $language = $anchorUser['language'];
            $out_users[] = $anchor;
            $json['users'] = $out_users;
            RedisClient::getInstance()->hSet('auto_chat_res', strval($uid), json_encode($json));
            $this->sendMsg($anchor, $uid, $language);
            UserTeaseDao::getInstance()->recordTease($anchor, $uid, null, 1);
            AutoChat::query()->insert([
                'uid' => $uid,
                'aid' => $anchor,
            ]);
        } else {
            $out_users[] = time();
            $json['users'] = $out_users;
            RedisClient::getInstance()->hSet('auto_chat_res', strval($uid), json_encode($json));
        }

    }

    function getPriorAnchor($uid, $maskIds)
    {
        if (config("envname") == 'dev') {
            // $sql = "SELECT uid FROM tb_anchor ORDER BY RAND() LIMIT 1";
            // $anchor = $model->findOneField($sql, 'uid');
            $anchor = User::query()->selectRaw('id,ext2')->where('sex', 2)->where('isdel', 0)->when(!empty($maskIds), function ($query) use ($maskIds) {
                $query->whereNotIn('id', $maskIds);
            })->inRandomOrder()->first();
        } else {
            // $sql = "SELECT u.id FROM tb_user u LEFT JOIN tb_user_token t ON t.uid=u.id WHERE u.online=1 AND u.sex=2 AND t.status=0 AND u.guild_num IN ('yq100161','yq100172','yq100105','yq100139')";
            $query = User::query()
                ->selectRaw('u.id,u.ext2')
                ->from('tb_user AS u')->leftJoin('tb_user_token AS t', 't.uid', '=', 'u.id')
                ->where('u.online', 1)
                ->where('u.sex', 2)
                ->where('t.status', 0)
                ->when(!empty($maskIds), function ($query) use ($maskIds) {
                    $query->whereNotIn('u.id', $maskIds);
                });

            $timeout = CommonSettingDao::getValue('woman_not_click_timeout') ?: 0;
            if ($timeout > 0) {
                // $sql .= " and unix_timestamp(now()) - u.click_time < " . $timeout;
                $query->whereRaw("unix_timestamp(now()) - u.click_time < $timeout");
            }

            // $push_level = $model->findOneField("SELECT push_level FROM tb_user WHERE id=$uid", 'push_level', 0);
            $push_level = User::query()->where('id', $uid)->value('push_level') ?? 0;
            switch ($push_level) {
                case 3:
                    // $sql .= " AND u.push_level IN (3,4)";
                    $query->whereIn('u.push_level', [3, 4]);
                    break;
                case 2:
                    // $sql .= " AND u.push_level IN (2,3,4)";
                    $query->whereIn('u.push_level', [2, 3, 4]);
                    break;
                case 1:
                    // $sql .= " AND u.push_level IN (1,2,3,4)";
                    $query->whereIn('u.push_level', [1, 2, 3, 4]);
                    break;
                default:
                    // $sql .= " AND u.push_level IN (0,1,2)";
                    $query->whereIn('u.push_level', [0, 1, 2]);
                    break;
            }

            $anchor = $query->inRandomOrder()->first();

            if (empty($anchor)) {
                // $sql = "SELECT u.id FROM tb_user u LEFT JOIN tb_user_token t ON t.uid=u.id WHERE u.online=1 AND u.sex=2 AND u.guild_num IN ('yq100161','yq100172','yq100105','yq100139')";
                $query2 = User::query()
                    ->selectRaw('u.id,u.ext2')
                    ->from('tb_user AS u')->leftJoin('tb_user_token AS t', 't.uid', '=', 'u.id')
                    ->where('u.online', 1)
                    ->where('u.sex', 2);
                if (!empty($maskIds)) {
                    $maskIds = array_unique($maskIds);
                    // $filter = implode(',', $users);
                    // $sql = $sql . " AND u.id NOT IN ($filter)";
                    $query2->whereNotIn('u.id', $maskIds);
                }

                if ($timeout > 0) {
                    // $sql .= " and unix_timestamp(now()) - u.click_time < " . $timeout;
                    $query2->whereRaw("unix_timestamp(now()) - u.click_time < $timeout");
                }

                // $rs = $model->query($sql);
                $anchor = $query2->inRandomOrder()->first();
            }
        }


        $anchor = modelToArray($anchor);
        if (empty($anchor)) {
            return null;
        }
        $ext = json_decode($anchor['ext2'], true);
        $language = (isset($ext['language']) && empty($ext['language'])) ? $ext['language'] : 'en';

        return ['id' => $anchor['id'], 'language' => $language];
    }


    function sendMsg($anchor, $uid, $language)
    {
        $result = GreetMasterDao::getInstance()->getRandOne($anchor);
        if (empty($result)) {
            // 记录脚本推送历史
            // [$script_id, $content] = (new AutoReplyModel())->getReplyContentWithId($anchor, 3);
            [$script_id, $content] = AutoReplyDao::getInstance()->getReplyContentWithId($anchor, 3, $language);
            $imageUrl = PhotoDao::getInstance()->getFemalePhotoPath($anchor);
        } else {
            $content = $result["text"];
            $imageUrl = $result["image_url"];
            $audioUrl = $result["audio_url"];
            $audioLen = $result["audio_len"];

        }

        PushMessageService::putYunXinSendMsgQueue($anchor, $uid, $content, 1, 3);
        //发送图片
        if ($imageUrl) {
            PushMessageService::putYunXinSendMsgQueue($anchor, $uid, $imageUrl, 3, 3);
        }

        //发送语音
        if (isset($audioUrl) && isset($audioLen)) {
            PushMessageService::putYunXinSendMsgQueue($anchor, $uid, $audioUrl, 2, 3, $audioLen);

        }

    }


}